package com.efun.framework.validate;

import com.baidu.unbiz.fluentvalidator.FluentValidator;
import com.baidu.unbiz.fluentvalidator.Result;
import com.baidu.unbiz.fluentvalidator.Validator;
import com.baidu.unbiz.fluentvalidator.ValidatorChain;
import com.efun.framework.web.ReturnT;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.baidu.unbiz.fluentvalidator.ResultCollectors.toSimple;

/**
 * 检验Controller中存在@RequestValidate注解的类和方法，
 * 这个方法是针对特有的request和response体系进行
 * Request的检验拦截类，直接适用在所有的Controller方法之前。
 * <pre>
 *      @RequestMapping("/")
 *      @RequestValidate
 *      public ReturnT<String> index(){}
 * </pre>
 * @author kinven on 17/8/20.
 */
public class RequestValidateInterceptor extends HandlerInterceptorAdapter {

    private static final String RequestValidateErrorKey = "RequestValidateErrorKey";

    private ValidatorManager validatorManager;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return super.preHandle(request, response, handler);
        }
        //通过method获取注解
        HandlerMethod method = (HandlerMethod)handler;
        RequestValidate validateAnnotation = method.getMethodAnnotation(RequestValidate.class);
        FluentValidator fluentValidator = FluentValidator.checkAll().failFast();

        //判定注解为空或者注解里面的,或者是检查不通过
        if(validateAnnotation != null) {
            //获取注解中的内容，使用fluentapi进行处理。
            //通过注册管理获取标签中的值和对应的bean
            Class[] clazzes = validateAnnotation.value();
            if(clazzes == null || clazzes.length == 0) {
                ValidatorChain defaultValidators = validatorManager.getDefaultValidator();
                if(!(null == defaultValidators || defaultValidators.getValidators().isEmpty())){
                    fluentValidator.on(request, defaultValidators).when(defaultValidators != null);
                }

            } else {
                for(Class<?> bean : clazzes){
                    Validator validator = validatorManager.getValidator(bean);
                    fluentValidator.on(request,validator).when(validator != null);
                }
            }
            Result result = fluentValidator.doValidate().result(toSimple());
            if(result.isSuccess()) {
                return true;
            }
            //todo 把结果写入到response中。
            ReturnT<String> returnT = ReturnT.FAIL;
            returnT.setContent(result.getErrors().get(0));
            request.setAttribute(RequestValidateErrorKey,returnT);
            return false;
            //把错误结果写入到ReturnT中，并输出到页面。
        }
        return super.preHandle(request, response, handler);
    }
}
